package com.gpt.article.controller;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.gpt.article.domain.GptSpiderDiy;
import com.gpt.article.domain.GptSpiderItem;
import com.gpt.article.service.IGptSpiderArticleContentService;
import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.GptSpiderArticle;
import com.gpt.article.service.IGptSpiderArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采集文章Controller
 *
 * @author zhuzi
 * @date 2023-10-24
 */
@RestController
@RequestMapping("/article/spiderArticle")
public class GptSpiderArticleController extends BaseController
{
    @Autowired
    private IGptSpiderArticleService gptSpiderArticleService;

    /**
     * 查询采集文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:list')")
    @GetMapping("/list")
    public TableDataInfo list(GptSpiderArticle gptSpiderArticle)
    {
        startPage();
        List<GptSpiderArticle> list = gptSpiderArticleService.selectGptSpiderArticleList(gptSpiderArticle);
        return getDataTable(list);
    }

    /**
     * 导出采集文章列表
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:export')")
    @Log(title = "采集文章", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GptSpiderArticle gptSpiderArticle)
    {
        List<GptSpiderArticle> list = gptSpiderArticleService.selectGptSpiderArticleList(gptSpiderArticle);
        ExcelUtil<GptSpiderArticle> util = new ExcelUtil<GptSpiderArticle>(GptSpiderArticle.class);
        util.exportExcel(response, list, "采集文章数据");
    }

    /**
     * 获取采集文章详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(gptSpiderArticleService.selectGptSpiderArticleById(id));
    }

    /**
     * 新增采集文章
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:add')")
    @Log(title = "采集文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody GptSpiderArticle gptSpiderArticle)
    {
        return toAjax(gptSpiderArticleService.insertGptSpiderArticle(gptSpiderArticle));
    }

    /**
     * 修改采集文章
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:edit')")
    @Log(title = "采集文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody GptSpiderArticle gptSpiderArticle)
    {
        return toAjax(gptSpiderArticleService.updateGptSpiderArticle(gptSpiderArticle));
    }

    /**
     * 删除采集文章
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:remove')")
    @Log(title = "采集文章", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(gptSpiderArticleService.deleteGptSpiderArticleByIds(ids));
    }

    @Log(title = "删除所有资源", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteAll")
    public AjaxResult removeAll(){
        return toAjax(gptSpiderArticleService.deleteAllSource());
    }

    /**
     * 获取采集来源
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:list')")
    @GetMapping("/getSpiderDiy")
    public AjaxResult getSpiderDiy()
    {
//        return success(gptSpiderDiyService.getSpiderItem());
        AjaxResult ajax = AjaxResult.success();
        List<GptSpiderDiy> spiderItemList = gptSpiderArticleService.getSpiderDiy();
        spiderItemList.forEach(e->{
            e.setName(e.getName()+"/生成规则");
        });
        for(GptSpiderDiy gptSpiderDiy:spiderItemList){

        }
        ajax.put("data", spiderItemList);
        return ajax;

    }


    /**
     * 根据gpt生成文章
     */
    @PreAuthorize("@ss.hasPermi('article:spiderArticle:add')")
    @Log(title = "生成文章", businessType = BusinessType.INSERT)
    @PostMapping("/genArticleByGpt")
    public AjaxResult genArticleByGpt(@RequestBody Map<String,Object> map) throws InterruptedException {
        //生成
//        Thread.sleep(5000);
        gptSpiderArticleService.toGenArticleByGpt(map);
//        System.out.println(map+"=============");
        return toAjax(true);
    }

    /**
     * 全量洗稿
     *
     * @param map
     *   洗稿参数条件
     */
    @Log(title = "执行全量洗稿", businessType = BusinessType.XIGAO)
    @PostMapping("/startXigaoAll")
    public AjaxResult startXigaoAll(@RequestBody Map<String,Object> map)
    {
        GptSpiderArticle gptSpiderArticle = new GptSpiderArticle();
        BeanMap beanMap = BeanMap.create(gptSpiderArticle);
        beanMap.putAll(map);
        gptSpiderArticleService.toStartXigaoAll(gptSpiderArticle,map);
        return success(true);
    }

    /**
     * 单个洗稿、批量洗稿
     */
    @Log(title = "执行洗稿", businessType = BusinessType.XIGAO)
    @PostMapping("/startXigao")
    public AjaxResult xigao(@RequestBody  Map<String,Object> map){
//
        String idstr = String.valueOf(map.get("ids"));
        String idst[] =  idstr.split(",");
        Long[] ids = stringToLong(idst);
//        Long[] ids = (Long[]) map.get("ids");
//        long[] ids = Arrays.asList(idst).stream().mapToLong(Long::valueOf).toArray();
        gptSpiderArticleService.startXigao(ids,map);
        return success(true);
    }

//    startXigao


    public Long[] stringToLong(String[] strings) {
        if (strings == null || strings.length < 1) {
            return null;
        }
        Long[] longs = new Long[strings.length];
        for (int i = 0; i < strings.length; i++) {
            String longidstr = strings[i].replaceAll("\\[","")
            .replaceAll("\\]","").replaceAll(" ","").trim();
            Long str = Long.valueOf(longidstr);
            longs[i] = str;
        }
        return longs;
    }


//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)

    @GetMapping("/checkConnet")
    public  boolean checkAble(){
        boolean reachable = false;
        try {
            String url = RuoYiConfig.getSdApi().replaceAll("http://","")
                    .replaceAll("https://","");
            System.out.println();
            System.out.println("使用keys:"+ new RuoYiConfig().getApiKeys());
            System.out.println("使用keys:"+ new RuoYiConfig().getApiKeys());
            InetAddress address = InetAddress.getByName(url);
             reachable = address.isReachable(5000);  // 超时时间为5秒
        } catch (IOException e) {
            reachable = false;
        }
        return reachable;
    }


}
